package de.fhhof.robot.control;

import java.io.*;

import de.fhhof.robot.control.cmd.concreate.AssemblyState;
import de.fhhof.robot.control.cmd.concreate.MessageState;

public class ApplicationStorage<T> {

	private static ApplicationStorage<AssemblyState> store = new ApplicationStorage<AssemblyState>();
	private static ApplicationStorage<MessageState> availability = new ApplicationStorage<MessageState>();
	
	public void store(T obj, String fileName){
			
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		
		try {
			File file = new File(fileName);
			if(!file.exists()){
				file.createNewFile();
			}
			fos = new FileOutputStream(fileName);
			out = new ObjectOutputStream(fos);
			out.writeObject(obj);
			out.close();
			//System.out.println("Object Persisted");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	
	}
	
	public T restore(String fileName){

		
		FileInputStream fis = null;
		ObjectInputStream in = null;
		T s = null;
		try {
			File file = new File(fileName);
			if(!file.exists()){
				return null;
			}
			
			fis = new FileInputStream(fileName);
			in = new ObjectInputStream(fis);
			 s = (T) in.readObject();
			in.close();
		} catch (IOException ex) {
			System.out.println("Error while reading recovery file: "+ex.getMessage());
		} 
		catch(ClassNotFoundException ex){
			ex.printStackTrace();
		}
		return  s;
	}
	public static ApplicationStorage<AssemblyState> getAssemblyState(){
		return store;
	}
	public static  ApplicationStorage<MessageState> getAvState(){
		return availability;
	}
	public static void main(String args[]){
		ApplicationStorage<AssemblyState> st = new ApplicationStorage<AssemblyState>();

		
		AssemblyState state2 = st.restore("a.data");
		System.out.println(state2.isAck1Sent());
		System.out.println(state2.isAck2Sent());
	}
}
